Page({
  data: {
    transactions: [],
    total: '0.00',
    pendingTotal: '0.00',
    editingRecord: null,
    statusMap: {
      '0': '处理中',
      '1': '已完成',
      '2': '已取消',
      'pending': '处理中',
      'completed': '已完成',
      'cancelled': '已取消'
    },
    typeMap: {
      'expense': '支出',
      'income': '收入',
      '0': '支出',
      '1': '收入'
    }
  },

  onLoad() {
    this.loadTransactions();
  },

  loadTransactions() {
    try {
      const transactions = wx.getStorageSync('transactions') || [];
      console.log('加载的交易数据:', transactions);

      const processed = transactions.map(item => {
        let statusClass = '';
        switch(item.status) {
          case '0': statusClass = 'status-pending'; break;
          case '1': statusClass = 'status-completed'; break;
          case '2': statusClass = 'status-cancelled'; break;
          default: statusClass = 'status-unknown';
        }

        let typeClass = '';
        switch(item.type) {
          case 'expense': typeClass = 'type-expense'; break;
          case 'income': typeClass = 'type-income'; break;
          default: typeClass = 'type-unknown';
        }

        return {
          ...item,
          displayStatus: this.data.statusMap[item.status] || '未知状态',
          displayType: this.data.typeMap[item.type] || '未知类型',
          displayAmount: item.amount ? parseFloat(item.amount).toFixed(2) : '0.00',
          originalAmount: item.originalAmount ? parseFloat(item.originalAmount).toFixed(2) : '0.00',
          statusClass,
          typeClass
        };
      });

      this.setData({
        transactions: processed,
        total: this.calculateTotal(transactions),
        pendingTotal: this.calculatePendingTotal(transactions)
      });
    } catch (e) {
      console.error('加载数据失败:', e);
    }
  },

  calculateTotal(transactions) {
    const total = transactions.reduce((sum, item) => {
      if (item.status === '0' || item.status === '1') {
        return sum + (parseFloat(item.amount) || 0);
      }
      return sum;
    }, 0);
    return total.toFixed(2);
  },

  calculatePendingTotal(transactions) {
    const pendingTotal = transactions.reduce((sum, item) => {
      if (item.status === '0') {
        return sum + (parseFloat(item.amount) || 0);
      }
      return sum;
    }, 0);
    return pendingTotal.toFixed(2);
  },

  editRecord(e) {
    const { id } = e.currentTarget.dataset;
    console.log('编辑记录:', id);
    
    wx.navigateTo({
      url: `/pages/edit-record/edit-record?id=${id}`,
      fail: (err) => {
        console.error('导航到编辑页面失败:', err);
        wx.showToast({
          title: '打开编辑页面失败',
          icon: 'none'
        });
      }
    });
  },

  deleteRecord(e) {
    const { id } = e.currentTarget.dataset;
    console.log('删除记录:', id);

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      success: (res) => {
        if (res.confirm) {
          try {
            const transactions = wx.getStorageSync('transactions') || [];
            const updatedTransactions = transactions.filter(item => item.id != id);
            wx.setStorageSync('transactions', updatedTransactions);
            
            this.loadTransactions();
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } catch (e) {
            console.error('删除记录失败:', e);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  viewDetail(e) {
    const { id } = e.currentTarget.dataset;
    console.log('查看详情:', id);
    
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
      fail: (err) => {
        console.error('导航到详情页面失败:', err);
        wx.showToast({
          title: '打开详情页面失败',
          icon: 'none'
        });
      }
    });
  },

  showStatusPicker() {
    const statusList = ['处理中', '已完成', '已取消'];
    wx.showActionSheet({
      itemList: statusList,
      success: (res) => {
        const statusValues = ['0', '1', '2'];
        const newStatus = statusValues[res.tapIndex];
        this.updateRecordStatus(newStatus);
      }
    });
  },

  showRateInput() {
    const currentRate = this.data.editingRecord.rate;
    wx.showModal({
      title: '修改汇率',
      placeholderText: String(currentRate),
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          const newRate = parseFloat(res.content);
          if (!isNaN(newRate) && newRate >= 0) {
            if (newRate > 1) {
              wx.showToast({
                title: '汇率不能大于1',
                icon: 'none'
              });
              return;
            }
            this.updateRecordRate(newRate);
          } else {
            wx.showToast({
              title: '请输入有效汇率',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  updateRecordStatus(newStatus) {
    try {
      console.log('更新状态:', newStatus);
      const { editingRecord } = this.data;
      const transactions = wx.getStorageSync('transactions') || [];

      const updatedTransactions = transactions.map(item => {
        if (item.id == editingRecord.id) {
          return { ...item, status: newStatus };
        }
        return item;
      });

      wx.setStorageSync('transactions', updatedTransactions);
      this.loadTransactions();

      wx.showToast({
        title: '状态已更新',
        icon: 'success'
      });
    } catch (e) {
      console.error('更新状态失败:', e);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  updateRecordRate(newRate) {
    try {
      console.log('更新汇率:', newRate);
      const { editingRecord } = this.data;
      const transactions = wx.getStorageSync('transactions') || [];

      const updatedTransactions = transactions.map(item => {
        if (item.id == editingRecord.id) {
          const originalAmount = parseFloat(item.originalAmount);
          const amount = originalAmount - (originalAmount * newRate);
          console.log('原始金额:', originalAmount, '新汇率:', newRate, '计算结果:', amount);

          return {
            ...item,
            rate: newRate,
            amount: amount
          };
        }
        return item;
      });

      wx.setStorageSync('transactions', updatedTransactions);
      this.loadTransactions();

      wx.showToast({
        title: '汇率已更新',
        icon: 'success'
      });
    } catch (e) {
      console.error('更新汇率失败:', e);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  navigateToAdd() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.navigateTo({
      url: '/pages/add-record/add-record',
      success: () => {
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('导航失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '打开失败',
          icon: 'none'
        });
      }
    });
  },

  onPullDownRefresh() {
    console.log('触发下拉刷新');
    this.loadTransactions();

    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      });
    }, 800);
  },

  copyAmount(e) {
    const { amount } = e.currentTarget.dataset;
    if (!amount) {
      wx.showToast({
        title: '复制失败，金额为空',
        icon: 'none'
      });
      return;
    }

    wx.setClipboardData({
      data: amount,
      success: () => {
        wx.showToast({
          title: '金额已复制',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('复制失败:', err);
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  }
});
